#include "BomHeaderParser.h"

#include "BoolParser.h"
#include "NameRefParser.h"
#include "QStringParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

BomHeaderParser::BomHeaderParser(
    QStringParser *&_assemblyParser
    , QStringParser *&_revisionParser
    , BoolParser *&_affectingParser
    , NameRefParser *&_stepRefParser
):    m_assemblyParser(_assemblyParser)
    , m_revisionParser(_revisionParser)
    , m_affectingParser(_affectingParser)
    , m_stepRefParser(_stepRefParser)
{

}

bool BomHeaderParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new BomHeader());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("assembly")))
    {
        data = reader->attributes().value(QStringLiteral("assembly"));
        if (!m_assemblyParser->parse(reader, data))
            return false;
        m_result->assembly = m_assemblyParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("assembly: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("revision")))
    {
        data = reader->attributes().value(QStringLiteral("revision"));
        if (!m_revisionParser->parse(reader, data))
            return false;
        m_result->revision = m_revisionParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("revision: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("affecting")))
    {
        data = reader->attributes().value(QStringLiteral("affecting"));
        if (!m_affectingParser->parse(reader, data))
            return false;
        m_result->affectingOptional = Optional<Bool>(m_affectingParser->result());
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (name == QStringLiteral("StepRef"))
        {
            if (!m_stepRefParser->parse(reader))
                return false;
            auto result = m_stepRefParser->result();
            m_result->stepRefList.append(result);
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

BomHeader *BomHeaderParser::result()
{
    return m_result.take();
}

}